<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="`业主房户关联 - ${ownerData?.ownerName || ''}`"
    width="1000px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="owner-household-container">
      <!-- 业主信息展示 - 仿照房户详情页面风格 -->
      <el-card class="owner-info-card" shadow="never">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="业主姓名">{{ ownerData?.ownerName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ ownerData?.idCard }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ ownerData?.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱地址">{{ ownerData?.email }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            <el-tag :type="ownerData?.gender === 1 ? 'primary' : ownerData?.gender === 2 ? 'success' : 'info'">
              {{ ownerData?.gender === 1 ? '男' : ownerData?.gender === 2 ? '女' : '未知' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="ownerData?.status === 1 ? 'success' : 'danger'">
              {{ ownerData?.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <!-- Tab页内容 -->
      <el-card class="detail-card" shadow="never" style="margin-top: 20px;">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card">
          <!-- 房产Tab -->
          <el-tab-pane label="房产" name="household">
            <div class="tab-content">
              <div class="tab-header">
                <el-button type="primary" size="small" @click="handleAddHousehold">
                  <el-icon><Plus /></el-icon>
                  新增关联
                </el-button>
              </div>
              
              <el-table
                :data="householdList"
                v-loading="loading"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="communityName" label="小区名称" min-width="150" />
                <el-table-column prop="buildingName" label="楼栋名称" min-width="120" />
                <el-table-column prop="unitName" label="单元名称" min-width="100" />
                <el-table-column prop="roomNumber" label="房间号" min-width="100" />
                <el-table-column prop="ownershipType" label="产权类型" min-width="120">
                  <template #default="{ row }">
                    <el-tag :type="getOwnershipTypeTag(row.ownershipType)">
                      {{ getOwnershipTypeText(row.ownershipType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="ownershipRatio" label="产权比例" min-width="100">
                  <template #default="{ row }">
                    {{ row.ownershipRatio }}%
                  </template>
                </el-table-column>
                <el-table-column prop="isPrimaryOwner" label="主业主" min-width="80">
                  <template #default="{ row }">
                    <el-tag :type="row.isPrimaryOwner ? 'success' : 'info'">
                      {{ row.isPrimaryOwner ? '是' : '否' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="certificateNumber" label="房产证号" min-width="180" />
                <el-table-column prop="certificateDate" label="发证日期" min-width="120" />
                <el-table-column label="操作" width="150" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleEditHousehold(row)">
                      <el-icon><Edit /></el-icon>
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="handleDeleteHousehold(row)">
                      <el-icon><Delete /></el-icon>
                      解除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 车辆Tab -->
          <el-tab-pane label="车辆" name="vehicle">
            <div class="tab-content">
              <el-table
                :data="vehicleList"
                v-loading="tabLoading.vehicle"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="plateNumber" label="车牌号" min-width="120" />
                <el-table-column prop="vehicleType" label="车辆类型" min-width="100" />
                <el-table-column prop="brand" label="品牌" min-width="100" />
                <el-table-column prop="model" label="型号" min-width="120" />
                <el-table-column prop="color" label="颜色" min-width="80" />
                <el-table-column prop="parkingSpace" label="停车位" min-width="120" />
                <el-table-column prop="status" label="状态" min-width="80">
                  <template #default="{ row }">
                    <el-tag :type="row.status === '正常' ? 'success' : 'warning'">
                      {{ row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="登记时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 家庭成员Tab -->
          <el-tab-pane label="家庭成员" name="family">
            <div class="tab-content">
              <el-table
                :data="familyList"
                v-loading="tabLoading.family"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="realName" label="姓名" min-width="100" />
                <el-table-column prop="phone" label="联系电话" min-width="120" />
                <el-table-column prop="identityNo" label="身份证号" min-width="180" />
                <el-table-column prop="residentTypeName" label="身份" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getResidentTypeTagType(row.residentType)">
                      {{ row.residentTypeName }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="moveInDate" label="入住日期" min-width="120" />
                <el-table-column prop="statusName" label="状态" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getResidentStatusTagType(row.status)">
                      {{ row.statusName }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 租客Tab -->
          <el-tab-pane label="租客" name="tenant">
            <div class="tab-content">
              <el-table
                :data="tenantList"
                v-loading="tabLoading.tenant"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="realName" label="姓名" min-width="100" />
                <el-table-column prop="phone" label="联系电话" min-width="120" />
                <el-table-column prop="identityNo" label="身份证号" min-width="180" />
                <el-table-column prop="residentTypeName" label="身份" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getResidentTypeTagType(row.residentType)">
                      {{ row.residentTypeName }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="moveInDate" label="入住日期" min-width="120" />
                <el-table-column prop="statusName" label="状态" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getResidentStatusTagType(row.status)">
                      {{ row.statusName }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 车位Tab -->
          <el-tab-pane label="车位" name="parking">
            <div class="tab-content">
              <el-table
                :data="parkingList"
                v-loading="tabLoading.parking"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="parkingNumber" label="车位号" min-width="120" />
                <el-table-column prop="parkingType" label="车位类型" min-width="100" />
                <el-table-column prop="area" label="面积" min-width="80" />
                <el-table-column prop="monthlyFee" label="月租费" min-width="100" />
                <el-table-column prop="status" label="状态" min-width="80">
                  <template #default="{ row }">
                    <el-tag :type="row.status === '已租' ? 'success' : 'info'">
                      {{ row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="rentalStartDate" label="租赁开始日期" min-width="140" />
                <el-table-column prop="rentalEndDate" label="租赁结束日期" min-width="140" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 报修Tab -->
          <el-tab-pane label="报修" name="repair">
            <div class="tab-content">
              <el-table
                :data="repairList"
                v-loading="tabLoading.repair"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="repairNo" label="报修单号" min-width="140" />
                <el-table-column prop="repairType" label="报修类型" min-width="100" />
                <el-table-column prop="description" label="问题描述" min-width="200">
                  <template #default="{ row }">
                    <el-tooltip
                      :content="row.description || '暂无描述'"
                      placement="top"
                      :disabled="false"
                      effect="dark"
                      :show-after="200"
                      :hide-after="0"
                    >
                      <div class="description-cell">
                        {{ row.description && row.description.length > 50 
                          ? row.description.substring(0, 50) + '...' 
                          : (row.description || '暂无描述') }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" min-width="80">
                  <template #default="{ row }">
                    <el-tag :type="getRepairStatusTagType(row.status)">
                      {{ row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="报修时间" min-width="160" />
                <el-table-column prop="expectedRepairTime" label="预计维修时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 投诉Tab -->
          <el-tab-pane label="投诉" name="complaint">
            <div class="tab-content">
              <el-table
                :data="complaintList"
                v-loading="tabLoading.complaint"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="complaintNo" label="投诉单号" min-width="140" />
                <el-table-column prop="complaintType" label="投诉类型" min-width="100" />
                <el-table-column prop="content" label="投诉内容" min-width="200">
                  <template #default="{ row }">
                    <el-tooltip
                      :content="row.content || '暂无内容'"
                      placement="top"
                      :disabled="false"
                      effect="dark"
                      :show-after="200"
                      :hide-after="0"
                    >
                      <div class="description-cell">
                        {{ row.content && row.content.length > 50 
                          ? row.content.substring(0, 50) + '...' 
                          : (row.content || '暂无内容') }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" min-width="80">
                  <template #default="{ row }">
                    <el-tag :type="getComplaintStatusTagType(row.status)">
                      {{ row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="投诉时间" min-width="160" />
                <el-table-column prop="handleTime" label="处理时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 物业费Tab -->
          <el-tab-pane label="物业费" name="propertyFee">
            <div class="tab-content">
              <el-table
                :data="propertyFeeList"
                v-loading="tabLoading.propertyFee"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="feeNo" label="收费单号" min-width="140" />
                <el-table-column prop="billingPeriod" label="计费月份" min-width="120" />
                <el-table-column prop="amount" label="费用金额" min-width="100" />
                <el-table-column prop="paidAmount" label="已支付金额" min-width="120" />
                <el-table-column prop="paymentStatus" label="缴费状态" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                      {{ row.paymentStatus }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                <el-table-column prop="createTime" label="创建时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 卫生费Tab -->
          <el-tab-pane label="卫生费" name="sanitationFee">
            <div class="tab-content">
              <el-table
                :data="sanitationFeeList"
                v-loading="tabLoading.sanitationFee"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="feeNo" label="收费单号" min-width="140" />
                <el-table-column prop="billingPeriod" label="计费月份" min-width="120" />
                <el-table-column prop="amount" label="费用金额" min-width="100" />
                <el-table-column prop="paidAmount" label="已支付金额" min-width="120" />
                <el-table-column prop="paymentStatus" label="缴费状态" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                      {{ row.paymentStatus }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                <el-table-column prop="createTime" label="创建时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 燃气费Tab -->
          <el-tab-pane label="燃气费" name="gasFee">
            <div class="tab-content">
              <el-table
                :data="gasFeeList"
                v-loading="tabLoading.gasFee"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="feeNo" label="收费单号" min-width="140" />
                <el-table-column prop="billingPeriod" label="计费月份" min-width="120" />
                <el-table-column prop="amount" label="费用金额" min-width="100" />
                <el-table-column prop="paidAmount" label="已支付金额" min-width="120" />
                <el-table-column prop="paymentStatus" label="缴费状态" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                      {{ row.paymentStatus }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                <el-table-column prop="createTime" label="创建时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 水费Tab -->
          <el-tab-pane label="水费" name="waterFee">
            <div class="tab-content">
              <el-table
                :data="waterFeeList"
                v-loading="tabLoading.waterFee"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="feeNo" label="收费单号" min-width="140" />
                <el-table-column prop="billingPeriod" label="计费月份" min-width="120" />
                <el-table-column prop="amount" label="费用金额" min-width="100" />
                <el-table-column prop="paidAmount" label="已支付金额" min-width="120" />
                <el-table-column prop="paymentStatus" label="缴费状态" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                      {{ row.paymentStatus }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                <el-table-column prop="createTime" label="创建时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
          
          <!-- 电费Tab -->
          <el-tab-pane label="电费" name="electricFee">
            <div class="tab-content">
              <el-table
                :data="electricFeeList"
                v-loading="tabLoading.electricFee"
                style="width: 100%"
                border
                stripe
              >
                <el-table-column prop="feeNo" label="收费单号" min-width="140" />
                <el-table-column prop="billingPeriod" label="计费月份" min-width="120" />
                <el-table-column prop="amount" label="费用金额" min-width="100" />
                <el-table-column prop="paidAmount" label="已支付金额" min-width="120" />
                <el-table-column prop="paymentStatus" label="缴费状态" min-width="100">
                  <template #default="{ row }">
                    <el-tag :type="getPaymentStatusTagType(row.paymentStatus)">
                      {{ row.paymentStatus }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="dueDate" label="缴费截止日期" min-width="140" />
                <el-table-column prop="createTime" label="创建时间" min-width="160" />
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    
    <!-- 房户关联表单对话框 -->
    <el-dialog
      v-model="formVisible"
      :title="isEdit ? '编辑房户关联' : '新增房户关联'"
      width="600px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="小区" prop="communityId">
          <el-select
            v-model="formData.communityId"
            placeholder="请选择小区"
            clearable
            style="width: 100%"
            :loading="communityLoading"
            @change="handleCommunityChange"
            :disabled="isEdit"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.communityName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="楼栋" prop="buildingId">
          <el-select
            v-model="formData.buildingId"
            placeholder="请选择楼栋"
            clearable
            style="width: 100%"
            :loading="buildingLoading"
            @change="handleBuildingChange"
            :disabled="!formData.communityId || isEdit"
          >
            <el-option
              v-for="item in buildingList"
              :key="item.id"
              :label="item.buildingName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="单元" prop="unitId">
          <el-select
            v-model="formData.unitId"
            placeholder="请选择单元"
            clearable
            style="width: 100%"
            :loading="unitLoading"
            @change="handleUnitChange"
            :disabled="!formData.buildingId || isEdit"
          >
            <el-option
              v-for="item in unitList"
              :key="item.id"
              :label="item.unitName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="房间" prop="roomId">
          <el-select
            v-model="formData.roomId"
            placeholder="请选择房间"
            clearable
            style="width: 100%"
            :loading="roomLoading"
            :disabled="!formData.unitId || isEdit"
          >
            <el-option
              v-for="item in roomList"
              :key="item.id"
              :label="item.roomNumber"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="产权类型" prop="ownershipType">
          <el-select v-model="formData.ownershipType" placeholder="请选择产权类型" style="width: 100%">
            <el-option label="完全产权" :value="1" />
            <el-option label="共有产权" :value="2" />
            <el-option label="部分产权" :value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="产权比例" prop="ownershipRatio">
          <el-input-number
            v-model="formData.ownershipRatio"
            :min="0"
            :max="100"
            :precision="2"
            style="width: 100%"
          />
          <span class="unit-text">%</span>
        </el-form-item>
        
        <el-form-item label="主业主" prop="isPrimaryOwner">
          <el-switch
            v-model="formData.isPrimaryOwner"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        
        <el-form-item label="房产证号" prop="certificateNumber">
          <el-input
            v-model="formData.certificateNumber"
            placeholder="请输入房产证号"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="发证日期" prop="certificateDate">
          <el-date-picker
            v-model="formData.certificateDate"
            type="date"
            placeholder="请选择发证日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="抵押信息" prop="mortgageInfo">
          <el-input
            v-model="formData.mortgageInfo"
            type="textarea"
            :rows="3"
            placeholder="请输入抵押信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import { ownerHouseholdApi } from '@/api/ownerHousehold'
import { communityApi } from '@/api/community'
import { buildingApi } from '@/api/building'
import { unitApi } from '@/api/unit'
import { householdApi } from '@/api/household'
import { dataScopeApi } from '@/api/property'
import { residentApi } from '@/api/resident'
import { repairOrderApi } from '@/api/repair'
import { propertyFeeApi } from '@/api/property/propertyFee'
import { sanitationFeeApi } from '@/api/property/sanitationFee'

// 定义props和emits
interface Props {
  visible: boolean
  ownerData?: any
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 用户store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const formVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// Tab切换相关
const activeTab = ref('household')

// 加载状态
const communityLoading = ref(false)
const buildingLoading = ref(false)
const unitLoading = ref(false)
const roomLoading = ref(false)

// Tab页加载状态
const tabLoading = ref({
  vehicle: false,
  family: false,
  tenant: false,
  parking: false,
  repair: false,
  complaint: false,
  propertyFee: false,
  sanitationFee: false,
  gasFee: false,
  waterFee: false,
  electricFee: false
})

// 计算属性
const isEdit = computed(() => !!currentHousehold.value)

// 当前编辑的房户关联
const currentHousehold = ref<any>(null)

// 房户关联列表
const householdList = ref<any[]>([])

// Tab页数据列表
const vehicleList = ref<any[]>([])
const familyList = ref<any[]>([])
const tenantList = ref<any[]>([])
const parkingList = ref<any[]>([])
const repairList = ref<any[]>([])
const complaintList = ref<any[]>([])
const propertyFeeList = ref<any[]>([])
const sanitationFeeList = ref<any[]>([])
const gasFeeList = ref<any[]>([])
const waterFeeList = ref<any[]>([])
const electricFeeList = ref<any[]>([])

// 加载房户关联列表 - 优化性能，添加缓存机制
const loadHouseholdList = async () => {
  if (!props.ownerData?.id) return
  
  try {
    loading.value = true
    const response = await ownerHouseholdApi.getOwnerHouseholds(props.ownerData.id)
    console.log('房户关联列表API响应:', response)
    
    if (response.code === 200 && response.data) {
      householdList.value = response.data
      console.log('房户关联列表数据:', householdList.value)
      
      // 保存数据到缓存，避免重复API调用
      saveDataToCache('household', response.data)
      
      // 检查每个房户关联数据的字段
      householdList.value.forEach((item, index) => {
        console.log(`房户关联数据[${index}]:`, {
          id: item.id,
          householdId: item.householdId,
          communityId: item.communityId,
          buildingId: item.buildingId,
          unitId: item.unitId,
          roomId: item.roomId,
          roomNumber: item.roomNumber,
          ownershipType: item.ownershipType,
          ownershipRatio: item.ownershipRatio
        })
      })
    } else {
      ElMessage.error(response.message || '加载房户关联列表失败')
    }
  } catch (error) {
    console.error('加载房户关联列表失败:', error)
    ElMessage.error('加载房户关联列表失败')
  } finally {
    loading.value = false
  }
}

// 表单数据 - 遵循Element Plus组件编码规范，使用undefined而不是null
const formData = reactive({
  communityId: undefined as number | undefined,
  buildingId: undefined as number | undefined,
  unitId: undefined as number | undefined,
  roomId: undefined as number | undefined,
  ownershipType: 1,
  ownershipRatio: 100, // 修复：改为数字类型，而不是字符串
  isPrimaryOwner: false,
  certificateNumber: '',
  certificateDate: '',
  mortgageInfo: ''
})

// 表单验证规则
const formRules: FormRules = {
  communityId: [
    { required: true, message: '请选择小区', trigger: 'change' }
  ],
  buildingId: [
    { required: true, message: '请选择楼栋', trigger: 'change' }
  ],
  unitId: [
    { required: true, message: '请选择单元', trigger: 'change' }
  ],
  roomId: [
    { required: true, message: '请选择房间', trigger: 'change' }
  ],
  ownershipType: [
    { required: true, message: '请选择产权类型', trigger: 'change' }
  ],
  ownershipRatio: [
    { required: true, message: '请输入产权比例', trigger: 'blur' }
  ],
  certificateNumber: [
    { required: true, message: '请输入房产证号', trigger: 'blur' }
  ],
  certificateDate: [
    { required: true, message: '请选择发证日期', trigger: 'change' }
  ]
}

// 四级联动数据
const communityList = ref<any[]>([])
const buildingList = ref<any[]>([])
const unitList = ref<any[]>([])
const roomList = ref<any[]>([])

// 获取产权类型标签
const getOwnershipTypeTag = (type: number) => {
  switch (type) {
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'info'
    default: return 'info'
  }
}

// 获取产权类型文本
const getOwnershipTypeText = (type: number) => {
  switch (type) {
    case 1: return '完全产权'
    case 2: return '共有产权'
    case 3: return '部分产权'
    default: return '未知'
  }
}

// 加载社区列表（根据数据权限）
const loadCommunityList = async () => {
  try {
    communityLoading.value = true
    
    // 获取用户数据权限信息
    const userDataScope = userStore.getUserDataScope()
    
    if (userDataScope.isSuperAdmin) {
      // 超级管理员可以看到所有社区
      const response = await communityApi.getCommunityList({ status: 1 })
      if (response.code === 200) {
        communityList.value = response.data || []
      }
    } else {
      // 物业公司管理员只能看到关联的社区
      const response = await dataScopeApi.getUserCommunities()
      if (response.code === 200 && response.data) {
        const communityIds = response.data
        if (communityIds.length > 0) {
          const communityResponse = await communityApi.getCommunityList({ 
            status: 1,
            ids: communityIds.join(',')
          })
          if (communityResponse.code === 200) {
            communityList.value = communityResponse.data || []
          }
        } else {
          communityList.value = []
        }
      }
    }
  } catch (error) {
    console.error('加载社区列表失败:', error)
    ElMessage.error('加载社区列表失败')
    communityList.value = []
  } finally {
    communityLoading.value = false
  }
}

// 小区变化处理
const handleCommunityChange = async (communityId: number, isEditMode = false) => {
  console.log('handleCommunityChange 被调用，communityId:', communityId, 'isEditMode:', isEditMode)
  
  // 编辑模式下不清空表单数据
  if (!isEditMode) {
    formData.buildingId = undefined
    formData.unitId = undefined
    formData.roomId = undefined
  }
  
  buildingList.value = []
  unitList.value = []
  roomList.value = []
  
  if (!communityId) {
    console.log('communityId为空，直接返回')
    return
  }
  
  try {
    buildingLoading.value = true
    console.log('开始加载楼栋数据，communityId:', communityId)
    const response = await buildingApi.getBuildingsByCommunity(communityId)
    console.log('楼栋API响应:', response)
    
    if (response.code === 200) {
      buildingList.value = response.data || []
      console.log('楼栋列表加载完成，数量:', buildingList.value.length)
    } else {
      console.error('楼栋API返回错误:', response.message)
      ElMessage.error(response.message || '加载楼栋列表失败')
      buildingList.value = []
    }
  } catch (error) {
    console.error('加载楼栋列表失败:', error)
    ElMessage.error('加载楼栋列表失败')
    buildingList.value = []
  } finally {
    buildingLoading.value = false
  }
}

// 楼栋变化处理
const handleBuildingChange = async (buildingId: number, isEditMode = false) => {
  console.log('handleBuildingChange 被调用，buildingId:', buildingId, 'isEditMode:', isEditMode)
  
  // 编辑模式下不清空表单数据
  if (!isEditMode) {
    formData.unitId = undefined
    formData.roomId = undefined
  }
  
  unitList.value = []
  roomList.value = []
  
  if (!buildingId) {
    console.log('buildingId为空，直接返回')
    return
  }
  
  try {
    unitLoading.value = true
    console.log('开始加载单元数据，buildingId:', buildingId)
    const response = await unitApi.getUnitsByBuilding(buildingId)
    console.log('单元API响应:', response)
    
    if (response.code === 200) {
      unitList.value = response.data || []
      console.log('单元列表加载完成，数量:', unitList.value.length)
    } else {
      console.error('单元API返回错误:', response.message)
      ElMessage.error(response.message || '加载单元列表失败')
      unitList.value = []
    }
  } catch (error) {
    console.error('加载单元列表失败:', error)
    ElMessage.error('加载单元列表失败')
    unitList.value = []
  } finally {
    unitLoading.value = false
  }
}

// 单元变化处理
const handleUnitChange = async (unitId: number, isEditMode = false) => {
  console.log('handleUnitChange 被调用，unitId:', unitId, 'isEditMode:', isEditMode)
  
  // 编辑模式下不清空表单数据
  if (!isEditMode) {
    formData.roomId = undefined
  }
  
  roomList.value = []
  
  if (!unitId) {
    console.log('unitId为空，直接返回')
    return
  }
  
  try {
    roomLoading.value = true
    console.log('开始加载房间数据，unitId:', unitId)
    const response = await householdApi.getHouseholdsByUnit(unitId)
    console.log('房间API响应:', response)
    
    if (response.code === 200) {
      roomList.value = response.data || []
      console.log('房间列表加载完成，数量:', roomList.value.length)
    } else {
      console.error('房间API返回错误:', response.message)
      ElMessage.error(response.message || '加载房间列表失败')
      roomList.value = []
    }
  } catch (error) {
    console.error('加载房间列表失败:', error)
    ElMessage.error('加载房间列表失败')
    roomList.value = []
  } finally {
    roomLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    communityId: undefined,
    buildingId: undefined,
    unitId: undefined,
    roomId: undefined,
    ownershipType: 1,
    ownershipRatio: 100, // 修复：确保是数字类型
    isPrimaryOwner: false,
    certificateNumber: '',
    certificateDate: '',
    mortgageInfo: ''
  })
  
  buildingList.value = []
  unitList.value = []
  roomList.value = []
  
  formRef.value?.clearValidate()
}

// 新增房户关联
const handleAddHousehold = () => {
  currentHousehold.value = null
  resetForm()
  // 加载社区列表
  loadCommunityList()
  formVisible.value = true
}

// 编辑房户关联
const handleEditHousehold = async (row: any) => {
  console.log('开始编辑房户关联:', row)
  // 确保currentHousehold包含正确的ownerId和householdId
  currentHousehold.value = { 
    ...row,
    ownerId: props.ownerData?.id, // 确保包含业主ID
    householdId: row.householdId // 确保包含房户ID
  }
  
  // 先加载社区列表
  await loadCommunityList()
  console.log('社区列表加载完成:', communityList.value)
  
  // 根据householdId获取房户详细信息
  if (row.householdId) {
    try {
      console.log('获取房户详细信息，householdId:', row.householdId)
      const householdResponse = await householdApi.getHouseholdDetail(row.householdId)
      console.log('房户详细信息响应:', householdResponse)
      
      if (householdResponse.code === 200 && householdResponse.data) {
        const householdDetail = householdResponse.data
        console.log('房户详细信息:', householdDetail)
        console.log('房户详细信息字段检查:', {
          communityId: householdDetail.communityId,
          buildingId: householdDetail.buildingId,
          unitId: householdDetail.unitId,
          roomNumber: householdDetail.roomNumber
        })
        
        // 根据房户详细信息加载四级联动数据
        if (householdDetail.communityId) {
          console.log('加载楼栋数据，社区ID:', householdDetail.communityId)
          await handleCommunityChange(householdDetail.communityId, true)
          console.log('楼栋列表加载完成:', buildingList.value)
          
          if (householdDetail.buildingId) {
            console.log('加载单元数据，楼栋ID:', householdDetail.buildingId)
            await handleBuildingChange(householdDetail.buildingId, true)
            console.log('单元列表加载完成:', unitList.value)
            
            if (householdDetail.unitId) {
              console.log('加载房间数据，单元ID:', householdDetail.unitId)
              await handleUnitChange(householdDetail.unitId, true)
              console.log('房间列表加载完成:', roomList.value)
            }
          }
        }
        
        // 等待所有数据加载完成后再设置表单数据
        await nextTick()
        
        // 设置表单数据 - 使用房户详细信息中的四级联动数据
        const formDataToSet = {
          communityId: householdDetail.communityId,
          buildingId: householdDetail.buildingId,
          unitId: householdDetail.unitId,
          roomId: row.householdId, // 使用householdId作为roomId
          ownershipType: row.ownershipType,
          ownershipRatio: Number(row.ownershipRatio) || 100,
          isPrimaryOwner: row.isPrimaryOwner,
          certificateNumber: row.certificateNumber || '',
          certificateDate: row.certificateDate || '',
          mortgageInfo: row.mortgageInfo || ''
        }
        
        console.log('设置表单数据:', formDataToSet)
        Object.assign(formData, formDataToSet)
        
        // 再次等待DOM更新
        await nextTick()
        console.log('编辑对话框打开，表单数据:', formData)
        
        formVisible.value = true
      } else {
        console.error('房户详情API返回错误:', householdResponse)
        ElMessage.error('获取房户详细信息失败')
      }
    } catch (error) {
      console.error('获取房户详细信息失败:', error)
      ElMessage.error('获取房户详细信息失败')
    }
  } else {
    console.error('房户ID为空:', row)
    ElMessage.error('房户ID不能为空')
  }
}

// 删除房户关联
const handleDeleteHousehold = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要解除业主与房户"${row.communityName}${row.buildingName}${row.unitName}${row.roomNumber}"的关联吗？`,
      '确认解除关联',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端API删除关联
    const response = await ownerHouseholdApi.removeOwnerHousehold(props.ownerData?.id, row.householdId)
    if (response.code === 200) {
      ElMessage.success('解除关联成功')
      // 重新加载列表
      await loadHouseholdList()
    } else {
      ElMessage.error(response.message || '解除关联失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解除关联失败:', error)
      ElMessage.error('解除关联失败')
    }
  }
}

// 提交表单
const handleSubmitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      // 编辑模式 - 不传递ownerId和householdId，只更新可编辑字段
      const response = await ownerHouseholdApi.updateOwnerHousehold(currentHousehold.value?.id, {
        ownershipType: formData.ownershipType,
        ownershipRatio: formData.ownershipRatio,
        isPrimaryOwner: formData.isPrimaryOwner,
        certificateNumber: formData.certificateNumber,
        certificateDate: formData.certificateDate,
        mortgageInfo: formData.mortgageInfo
      })
      
      if (response.code === 200) {
        const index = householdList.value.findIndex(item => item.id === currentHousehold.value?.id)
        if (index > -1) {
          householdList.value[index] = {
            ...currentHousehold.value,
            ...formData,
            communityName: communityList.value.find(c => c.id === formData.communityId)?.communityName,
            buildingName: buildingList.value.find(b => b.id === formData.buildingId)?.buildingName,
            unitName: unitList.value.find(u => u.id === formData.unitId)?.unitName,
            roomNumber: roomList.value.find(r => r.id === formData.roomId)?.roomNumber
          }
        }
        ElMessage.success('更新成功')
        // 重新加载列表
        await loadHouseholdList()
      } else {
        ElMessage.error(response.message || '更新失败')
      }
    } else {
      // 新增模式
      const response = await ownerHouseholdApi.createOwnerHousehold({
        ownerId: props.ownerData?.id,
        householdId: formData.roomId,
        ownershipType: formData.ownershipType,
        ownershipRatio: formData.ownershipRatio,
        isPrimaryOwner: formData.isPrimaryOwner,
        certificateNumber: formData.certificateNumber,
        certificateDate: formData.certificateDate,
        mortgageInfo: formData.mortgageInfo
      })
      
      if (response.code === 200) {
        ElMessage.success('创建成功')
        // 重新加载列表
        await loadHouseholdList()
      } else {
        ElMessage.error(response.message || '创建失败')
      }
    }
    
    formVisible.value = false
    emit('success')
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('表单提交失败')
  } finally {
    submitLoading.value = false
  }
}

// 重置Tab页数据缓存
const resetTabDataCache = () => {
  Object.keys(tabDataLoaded.value).forEach(key => {
    tabDataLoaded.value[key as keyof typeof tabDataLoaded.value] = false
  })
  // 清空数据缓存
  Object.keys(dataCache.value).forEach(key => {
    dataCache.value[key as keyof typeof dataCache.value] = null
  })
  console.log('Tab页数据缓存已重置')
}

// 从缓存中恢复数据
const restoreDataFromCache = (tabName: string) => {
  const cacheKey = `${tabName}Data` as keyof typeof dataCache.value
  const cachedData = dataCache.value[cacheKey]
  
  if (cachedData) {
    console.log(`从缓存恢复 ${tabName} 数据`)
    switch (tabName) {
      case 'household':
        householdList.value = cachedData
        break
      case 'vehicle':
        vehicleList.value = cachedData
        break
      case 'family':
        familyList.value = cachedData
        break
      case 'tenant':
        tenantList.value = cachedData
        break
      case 'parking':
        parkingList.value = cachedData
        break
      case 'repair':
        repairList.value = cachedData
        break
      case 'complaint':
        complaintList.value = cachedData
        break
      case 'propertyFee':
        propertyFeeList.value = cachedData
        break
      case 'sanitationFee':
        sanitationFeeList.value = cachedData
        break
      case 'gasFee':
        gasFeeList.value = cachedData
        break
      case 'waterFee':
        waterFeeList.value = cachedData
        break
      case 'electricFee':
        electricFeeList.value = cachedData
        break
    }
  }
}

// 保存数据到缓存
const saveDataToCache = (tabName: string, data: any) => {
  const cacheKey = `${tabName}Data` as keyof typeof dataCache.value
  dataCache.value[cacheKey] = data
  console.log(`数据已保存到缓存: ${tabName}`)
}

// 监听对话框显示状态，加载房户关联列表
watch(() => props.visible, async (newVisible) => {
  if (newVisible && props.ownerData?.id) {
    // 重置Tab页数据缓存
    resetTabDataCache()
    // 同时加载房户关联列表和社区列表
    await Promise.all([
      loadHouseholdList(),
      loadCommunityList()
    ])
  } else if (!newVisible) {
    // 对话框关闭时重置缓存
    resetTabDataCache()
  }
})

// 初始化函数
const initializeData = async () => {
  if (props.ownerData?.id) {
    try {
      // 并行加载数据以提高性能
      await Promise.all([
        loadHouseholdList(),
        loadCommunityList()
      ])
    } catch (error) {
      console.error('初始化数据失败:', error)
      ElMessage.error('初始化数据失败')
    }
  }
}

// Tab页点击处理 - 遵循Element Plus组件编码规范
const handleTabClick = (tab: any) => {
  console.log('Tab点击事件触发，tab对象:', tab)
  // Tab切换和数据加载由watch监听器处理，这里只记录点击事件
}

// 监听activeTab变化，处理Tab切换时的数据加载
watch(activeTab, async (newTab, oldTab) => {
  console.log('Tab切换监听触发:', { oldTab, newTab })
  
  if (newTab && newTab !== oldTab && props.ownerData?.id) {
    console.log('开始加载Tab页数据:', newTab)
    await loadTabData(newTab)
  }
}, { immediate: false })

// Tab页数据加载状态缓存
const tabDataLoaded = ref({
  household: false,
  vehicle: false,
  family: false,
  tenant: false,
  parking: false,
  repair: false,
  complaint: false,
  propertyFee: false,
  sanitationFee: false,
  gasFee: false,
  waterFee: false,
  electricFee: false
})

// 数据缓存 - 避免重复API调用
const dataCache = ref({
  householdData: null as any,
  vehicleData: null as any,
  familyData: null as any,
  tenantData: null as any,
  parkingData: null as any,
  repairData: null as any,
  complaintData: null as any,
  propertyFeeData: null as any,
  sanitationFeeData: null as any,
  gasFeeData: null as any,
  waterFeeData: null as any,
  electricFeeData: null as any
})

// 加载Tab页数据 - 优化性能，避免重复API调用
const loadTabData = async (tabName: string) => {
  if (!props.ownerData?.id) {
    console.log('没有业主数据，无法加载Tab页数据')
    return
  }
  
  if (!tabName) {
    console.warn('Tab名称为空，无法加载数据')
    return
  }
  
  const ownerId = props.ownerData.id
  console.log('业主ID:', ownerId, 'Tab名称:', tabName)
  
  // 检查是否已经加载过数据，避免重复加载
  if (tabDataLoaded.value[tabName as keyof typeof tabDataLoaded.value]) {
    console.log(`Tab页 ${tabName} 数据已加载，使用缓存数据`)
    // 从缓存中恢复数据
    restoreDataFromCache(tabName)
    return
  }
  
  console.log(`开始加载Tab页 ${tabName} 数据`)
  
  try {
    switch (tabName) {
      case 'household':
        // 房产Tab页特殊处理：如果数据已加载，直接使用缓存
        if (tabDataLoaded.value.household) {
          console.log('房产Tab页数据已加载，使用缓存数据')
          restoreDataFromCache('household')
        } else {
          await loadHouseholdList()
        }
        break
      case 'vehicle':
        await loadVehicleList()
        break
      case 'family':
        await loadFamilyList()
        break
      case 'tenant':
        await loadTenantList()
        break
      case 'parking':
        await loadParkingList()
        break
      case 'repair':
        await loadRepairList()
        break
      case 'complaint':
        await loadComplaintList()
        break
      case 'propertyFee':
        await loadPropertyFeeList()
        break
      case 'sanitationFee':
        await loadSanitationFeeList()
        break
      case 'gasFee':
        await loadGasFeeList()
        break
      case 'waterFee':
        await loadWaterFeeList()
        break
      case 'electricFee':
        await loadElectricFeeList()
        break
      default:
        console.warn(`未知的Tab页名称: ${tabName}`)
        return
    }
    
    // 标记数据已加载
    tabDataLoaded.value[tabName as keyof typeof tabDataLoaded.value] = true
    console.log(`Tab页 ${tabName} 数据加载完成`)
  } catch (error) {
    console.error(`Tab页 ${tabName} 数据加载失败:`, error)
    // 加载失败时重置缓存状态，允许重试
    tabDataLoaded.value[tabName as keyof typeof tabDataLoaded.value] = false
  }
}

// 加载车辆列表（静态数据）
const loadVehicleList = async () => {
  try {
    tabLoading.value.vehicle = true
    // 模拟静态数据
    vehicleList.value = [
      {
        plateNumber: '京A12345',
        vehicleType: '小型汽车',
        brand: '丰田',
        model: '凯美瑞',
        color: '白色',
        parkingSpace: 'A001',
        status: '正常',
        createTime: '2024-01-15 10:30:00'
      },
      {
        plateNumber: '京B67890',
        vehicleType: '小型汽车',
        brand: '本田',
        model: '雅阁',
        color: '黑色',
        parkingSpace: 'A002',
        status: '正常',
        createTime: '2024-02-20 14:20:00'
      }
    ]
  } catch (error) {
    console.error('加载车辆列表失败:', error)
    ElMessage.error('加载车辆列表失败')
  } finally {
    tabLoading.value.vehicle = false
  }
}

// 加载家庭成员列表
const loadFamilyList = async () => {
  try {
    tabLoading.value.family = true
    // 使用userId而不是ownerId，符合业务逻辑
    const response = await residentApi.getFamilyMembersByUserId(props.ownerData.userId)
    if (response.code === 200) {
      familyList.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载家庭成员列表失败')
      familyList.value = []
    }
  } catch (error) {
    console.error('加载家庭成员列表失败:', error)
    ElMessage.error('加载家庭成员列表失败')
    familyList.value = []
  } finally {
    tabLoading.value.family = false
  }
}

// 加载租客列表
const loadTenantList = async () => {
  try {
    tabLoading.value.tenant = true
    // 使用userId而不是ownerId，符合业务逻辑
    const response = await residentApi.getTenantsByUserId(props.ownerData.userId)
    if (response.code === 200) {
      tenantList.value = response.data || []
    } else {
      ElMessage.error(response.message || '加载租客列表失败')
      tenantList.value = []
    }
  } catch (error) {
    console.error('加载租客列表失败:', error)
    ElMessage.error('加载租客列表失败')
    tenantList.value = []
  } finally {
    tabLoading.value.tenant = false
  }
}

// 加载车位列表（静态数据）
const loadParkingList = async () => {
  try {
    tabLoading.value.parking = true
    // 模拟静态数据
    parkingList.value = [
      {
        parkingNumber: 'A001',
        parkingType: '地下车位',
        area: '15.5',
        monthlyFee: '300',
        status: '已租',
        rentalStartDate: '2024-01-01',
        rentalEndDate: '2024-12-31'
      },
      {
        parkingNumber: 'A002',
        parkingType: '地面车位',
        area: '12.0',
        monthlyFee: '200',
        status: '空闲',
        rentalStartDate: '',
        rentalEndDate: ''
      }
    ]
  } catch (error) {
    console.error('加载车位列表失败:', error)
    ElMessage.error('加载车位列表失败')
  } finally {
    tabLoading.value.parking = false
  }
}

// 加载报修列表
const loadRepairList = async () => {
  if (!props.ownerData?.id) {
    console.log('没有业主数据，无法加载报修列表')
    return
  }
  
  try {
    tabLoading.value.repair = true
    console.log('开始加载报修列表，业主ID:', props.ownerData.id)
    
    // 优先使用缓存的房户数据，避免重复API调用
    let householdData = dataCache.value.householdData
    if (!householdData) {
      console.log('缓存中没有房户数据，重新获取')
      const householdResponse = await ownerHouseholdApi.getOwnerHouseholds(props.ownerData.id)
      if (householdResponse.code === 200 && householdResponse.data) {
        householdData = householdResponse.data
        // 保存到缓存
        saveDataToCache('household', householdData)
      } else {
        console.error('获取房户关联失败:', householdResponse.message)
        ElMessage.error(householdResponse.message || '获取房户关联失败')
        repairList.value = []
        return
      }
    } else {
      console.log('使用缓存的房户数据')
    }
    
    if (householdData && householdData.length > 0) {
      const householdIds = householdData.map((item: any) => item.householdId)
      console.log('获取到的房户ID列表:', householdIds)
      
      if (householdIds.length > 0) {
        // 调用报修API获取报修列表
        const repairResponse = await repairOrderApi.getRepairOrderList({
          householdIds: householdIds.join(','),
          current: 1,
          size: 100
        })
        
        if (repairResponse.code === 200) {
          repairList.value = repairResponse.data?.records || []
          // 保存报修数据到缓存
          saveDataToCache('repair', repairList.value)
          console.log('报修列表加载完成，数量:', repairList.value.length)
        } else {
          console.error('报修API返回错误:', repairResponse.message)
          ElMessage.error(repairResponse.message || '加载报修列表失败')
          repairList.value = []
        }
      } else {
        console.log('没有关联的房户，报修列表为空')
        repairList.value = []
      }
    } else {
      console.log('没有关联的房户，报修列表为空')
      repairList.value = []
    }
  } catch (error) {
    console.error('加载报修列表失败:', error)
    ElMessage.error('加载报修列表失败')
    repairList.value = []
  } finally {
    tabLoading.value.repair = false
  }
}

// 加载投诉列表（静态数据）
const loadComplaintList = async () => {
  try {
    tabLoading.value.complaint = true
    // 模拟静态数据
    complaintList.value = [
      {
        complaintNo: 'TS202401001',
        complaintType: '噪音投诉',
        content: '楼上装修噪音过大，影响正常生活',
        status: '已处理',
        createTime: '2024-01-15 09:30:00',
        handleTime: '2024-01-16 14:20:00'
      }
    ]
  } catch (error) {
    console.error('加载投诉列表失败:', error)
    ElMessage.error('加载投诉列表失败')
  } finally {
    tabLoading.value.complaint = false
  }
}

// 加载物业费列表
const loadPropertyFeeList = async () => {
  if (!props.ownerData?.id) {
    console.log('没有业主数据，无法加载物业费列表')
    return
  }
  
  try {
    tabLoading.value.propertyFee = true
    console.log('开始加载物业费列表，业主ID:', props.ownerData.id)
    
    // 优先使用缓存的房户数据，避免重复API调用
    let householdData = dataCache.value.householdData
    if (!householdData) {
      console.log('缓存中没有房户数据，重新获取')
      const householdResponse = await ownerHouseholdApi.getOwnerHouseholds(props.ownerData.id)
      if (householdResponse.code === 200 && householdResponse.data) {
        householdData = householdResponse.data
        // 保存到缓存
        saveDataToCache('household', householdData)
      } else {
        console.error('获取房户关联失败:', householdResponse.message)
        ElMessage.error(householdResponse.message || '获取房户关联失败')
        propertyFeeList.value = []
        return
      }
    } else {
      console.log('使用缓存的房户数据')
    }
    
    if (householdData && householdData.length > 0) {
      const householdIds = householdData.map((item: any) => item.householdId)
      console.log('获取到的房户ID列表:', householdIds)
      
      if (householdIds.length > 0) {
        // 调用物业费API获取物业费列表
        const propertyFeeResponse = await propertyFeeApi.getPropertyFeePage({
          householdIds: householdIds.join(','),
          current: 1,
          size: 100
        })
        
        if (propertyFeeResponse.code === 200) {
          propertyFeeList.value = propertyFeeResponse.data?.records || []
          // 保存物业费数据到缓存
          saveDataToCache('propertyFee', propertyFeeList.value)
          console.log('物业费列表加载完成，数量:', propertyFeeList.value.length)
        } else {
          console.error('物业费API返回错误:', propertyFeeResponse.message)
          ElMessage.error(propertyFeeResponse.message || '加载物业费列表失败')
          propertyFeeList.value = []
        }
      } else {
        console.log('没有关联的房户，物业费列表为空')
        propertyFeeList.value = []
      }
    } else {
      console.log('没有关联的房户，物业费列表为空')
      propertyFeeList.value = []
    }
  } catch (error) {
    console.error('加载物业费列表失败:', error)
    ElMessage.error('加载物业费列表失败')
    propertyFeeList.value = []
  } finally {
    tabLoading.value.propertyFee = false
  }
}

// 加载卫生费列表
const loadSanitationFeeList = async () => {
  if (!props.ownerData?.id) {
    console.log('没有业主数据，无法加载卫生费列表')
    return
  }
  
  try {
    tabLoading.value.sanitationFee = true
    console.log('开始加载卫生费列表，业主ID:', props.ownerData.id)
    
    // 优先使用缓存的房户数据，避免重复API调用
    let householdData = dataCache.value.householdData
    if (!householdData) {
      console.log('缓存中没有房户数据，重新获取')
      const householdResponse = await ownerHouseholdApi.getOwnerHouseholds(props.ownerData.id)
      if (householdResponse.code === 200 && householdResponse.data) {
        householdData = householdResponse.data
        // 保存到缓存
        saveDataToCache('household', householdData)
      } else {
        console.error('获取房户关联失败:', householdResponse.message)
        ElMessage.error(householdResponse.message || '获取房户关联失败')
        sanitationFeeList.value = []
        return
      }
    } else {
      console.log('使用缓存的房户数据')
    }
    
    if (householdData && householdData.length > 0) {
      const householdIds = householdData.map((item: any) => item.householdId)
      console.log('获取到的房户ID列表:', householdIds)
      
      if (householdIds.length > 0) {
        // 调用卫生费API获取卫生费列表
        const sanitationFeeResponse = await sanitationFeeApi.getSanitationFeePage({
          householdIds: householdIds.join(','),
          current: 1,
          size: 100
        })
        
        if (sanitationFeeResponse.code === 200) {
          sanitationFeeList.value = sanitationFeeResponse.data?.records || []
          // 保存卫生费数据到缓存
          saveDataToCache('sanitationFee', sanitationFeeList.value)
          console.log('卫生费列表加载完成，数量:', sanitationFeeList.value.length)
        } else {
          console.error('卫生费API返回错误:', sanitationFeeResponse.message)
          ElMessage.error(sanitationFeeResponse.message || '加载卫生费列表失败')
          sanitationFeeList.value = []
        }
      } else {
        console.log('没有关联的房户，卫生费列表为空')
        sanitationFeeList.value = []
      }
    } else {
      console.log('没有关联的房户，卫生费列表为空')
      sanitationFeeList.value = []
    }
  } catch (error) {
    console.error('加载卫生费列表失败:', error)
    ElMessage.error('加载卫生费列表失败')
    sanitationFeeList.value = []
  } finally {
    tabLoading.value.sanitationFee = false
  }
}

// 加载燃气费列表（静态数据）
const loadGasFeeList = async () => {
  try {
    tabLoading.value.gasFee = true
    // 模拟静态数据
    gasFeeList.value = [
      {
        feeNo: 'GAS202401001',
        billingPeriod: '2024-01',
        amount: '120.50',
        paidAmount: '120.50',
        paymentStatus: '已缴费',
        dueDate: '2024-02-15',
        createTime: '2024-01-01 00:00:00'
      }
    ]
  } catch (error) {
    console.error('加载燃气费列表失败:', error)
    ElMessage.error('加载燃气费列表失败')
  } finally {
    tabLoading.value.gasFee = false
  }
}

// 加载水费列表（静态数据）
const loadWaterFeeList = async () => {
  try {
    tabLoading.value.waterFee = true
    // 模拟静态数据
    waterFeeList.value = [
      {
        feeNo: 'WATER202401001',
        billingPeriod: '2024-01',
        amount: '85.30',
        paidAmount: '85.30',
        paymentStatus: '已缴费',
        dueDate: '2024-02-15',
        createTime: '2024-01-01 00:00:00'
      }
    ]
  } catch (error) {
    console.error('加载水费列表失败:', error)
    ElMessage.error('加载水费列表失败')
  } finally {
    tabLoading.value.waterFee = false
  }
}

// 加载电费列表（静态数据）
const loadElectricFeeList = async () => {
  try {
    tabLoading.value.electricFee = true
    // 模拟静态数据
    electricFeeList.value = [
      {
        feeNo: 'ELEC202401001',
        billingPeriod: '2024-01',
        amount: '156.80',
        paidAmount: '156.80',
        paymentStatus: '已缴费',
        dueDate: '2024-02-15',
        createTime: '2024-01-01 00:00:00'
      }
    ]
  } catch (error) {
    console.error('加载电费列表失败:', error)
    ElMessage.error('加载电费列表失败')
  } finally {
    tabLoading.value.electricFee = false
  }
}

// 获取住户类型标签类型
const getResidentTypeTagType = (type: number) => {
  switch (type) {
    case 1: return 'primary'
    case 2: return 'success'
    case 3: return 'warning'
    case 4: return 'info'
    default: return 'info'
  }
}

// 获取住户状态标签类型
const getResidentStatusTagType = (status: number) => {
  switch (status) {
    case 1: return 'success'
    case 0: return 'danger'
    default: return 'info'
  }
}

// 获取报修状态标签类型
const getRepairStatusTagType = (status: string) => {
  switch (status) {
    case '待处理': return 'warning'
    case '处理中': return 'primary'
    case '已完成': return 'success'
    case '已取消': return 'info'
    default: return 'info'
  }
}

// 获取投诉状态标签类型
const getComplaintStatusTagType = (status: string) => {
  switch (status) {
    case '待处理': return 'warning'
    case '处理中': return 'primary'
    case '已处理': return 'success'
    case '已关闭': return 'info'
    default: return 'info'
  }
}

// 获取缴费状态标签类型
const getPaymentStatusTagType = (status: string) => {
  switch (status) {
    case '已缴费': return 'success'
    case '未缴费': return 'danger'
    case '部分缴费': return 'warning'
    default: return 'info'
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  if (props.visible && props.ownerData?.id) {
    initializeData()
  }
})
</script>

<style scoped>
.owner-household-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.owner-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tab-content {
  padding: 20px 0;
}

.tab-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.unit-text {
  margin-left: 10px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}

.description-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  transition: color 0.3s ease;
}

.description-cell:hover {
  color: #409eff;
}
</style>
